package mailbox

import (
	"com.lh.mail.service/pb/mailbox"
	"context"
	"fmt"
	"net/smtp"
	"strings"
)

func (mail *Mailbox) SendMail(ctx context.Context, req *mailbox.SendRequest) (*mailbox.NoResponse, error) {
	users := append(req.GetRecipient(), req.GetCc()...)
	users = append(users, req.GetBcc()...)
	// 设置邮件内容
	contentType := "text/plain"
	if req.GetIsHtml() {
		contentType = "text/html"
	}
	message := fmt.Sprintf("From: %s\r\n", req.GetSender())
	message += fmt.Sprintf("To: %s\r\n", strings.Join(req.GetRecipient(), ","))
	if len(req.Cc) > 0 {
		message += fmt.Sprintf("Cc: %s\r\n", strings.Join(req.GetCc(), ","))
	}
	message += fmt.Sprintf("Subject: %s\r\n", req.GetSubject())
	message += fmt.Sprintf("MIME-Version: 1.0\r\n")
	message += fmt.Sprintf("Content-Type: %s; charset=UTF-8\r\n", contentType)
	message += fmt.Sprintf("\r\n%s", req.GetBody())
	//md, ok := metadata.FromIncomingContext(c)
	//if !ok {
	//	return nil, errors.New("no metadata")
	//}
	//sid := md.Get("sid")
	//if len(sid) < 1 {
	//	return nil, errors.New("no sid")
	//}
	serve := &mailbox.ServeConfig{
		Host:     "smtp.163.com",
		Port:     25,
		User:     "allkic@163.com",
		Password: "PPU9ADFtKmFRASw6",
	}
	fmt.Println(serve)
	//red := redis.Init()
	//if !p.isUser && tools.ValidateToken(c) {
	//	serve.Host = "localhost"
	//	serve.Port = "9006"
	//} else if p.isUser {
	//	res, err := red.GetRow(fmt.Sprintf("mail_%s", sid[0]))
	//	if err != nil {
	//		return nil, err
	//	}
	//	var list mailbox.MailUserInfo
	//	if err = proto.Unmarshal(res.GetData(), &list); err != nil {
	//		return nil, err
	//	}
	//	serve, ok = list.GetList()[r.GetSender()]
	//	if !ok {
	//		return nil, errors.New("no data")
	//	}
	//}
	auth := smtp.PlainAuth("", serve.User, serve.Password, serve.Host)
	fmt.Println(auth)
	err := smtp.SendMail(fmt.Sprintf("%s:%d", serve.Host, serve.Port), auth, req.Sender, req.Recipient, []byte(message))
	fmt.Println(err)
	return &mailbox.NoResponse{}, err
}
